<template>
  <div class="container">
    <uni-card
        v-for="(article, index) in articles"
        :key="index"
        :title="article.title"
        :sub-title="article.subTitle"
        :extra="`发布人: ${article.username}`"
        padding="10px 0"
        :thumbnail="article.thumbnail"
        class="uni-card-extra"
    >
      <div style="width: 100%; height: 200px; overflow-y: auto;">
        <div v-html="formattedContent(article.content, article.showFullContent)"></div>
      </div>
      <view slot="actions" class="card-actions">
        <div
            class="action-area"
            @click="actionsClick('点赞', article)"
        >
          <uni-icons type="heart-filled" size="21" :color="article.likeColor"></uni-icons>
          <text class="action-button-text">{{ article.likeNum }}</text>
        </div>
        <div
            class="action-area"
            @click="actionsClick('收藏', article)"
        >
          <uni-icons type="star-filled" size="21" :color="article.favoriteColor"></uni-icons>
          <text class="action-button-text">{{ article.favoriteNum }}</text>
        </div>
      </view>
    </uni-card>
  </div>
</template>

<script>
import { selectarticles, updateArticle } from "./api/Articles";

export default {
  data() {
    return {
      articles: [], // 定义数组接收列表
    };
  },
  mounted() {
    // 在组件挂载后查询文章信息
    this.queryArticles();
  },
  methods: {
    // 查询文章信息
    async queryArticles() {
      try {
        const res = await selectarticles();
        console.log('开始查询');
        if (res.data && res.data.length > 0) {
          this.articles = res.data.map(article => ({
            ...article,
            liked: false,
            favorited: false,
            likeColor: '#999', // 默认颜色
            favoriteColor: '#999',
            content: this.formatContentImages(article.content), // 格式化图片
            showFullContent: false, // 控制是否显示完整内容
            likeNum: article.likeNum || 0, // 确保 likeNum 存在并初始化为0
            favoriteNum: article.favoriteNum || 0 // 确保 favoriteNum 存在并初始化为0
          }));
          console.log('查询文章信息', this.articles);
        } else {
          console.log('未找到文章信息');
          uni.showToast({
            title: '暂时没有发布文章',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取文章详情页失败', error);
        uni.showToast({
          title: '网络延迟，请稍后重试',
          icon: 'none'
        });
      }
    },
    formatContentImages(content) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(content, 'text/html');
      const imgElements = doc.querySelectorAll('img');

      imgElements.forEach(img => {
        img.style.width = '100%';
        img.style.height = 'auto';
        img.style.marginBottom = '10px'; // 添加边距
      });

      return doc.body.innerHTML;
    },
    formattedContent(content, showFullContent) {
      return content; // 直接返回原始内容
    },
    actionsClick(action, article) {
      console.log(`${action} 操作前`, article);
      if (action === '点赞') {
        article.liked = !article.liked;
        article.likeColor = article.liked ? 'red' : '#999';
        article.likeNum += article.liked ? 1 : -1;
      } else if (action === '收藏') {
        article.favorited = !article.favorited;
        article.favoriteColor = article.favorited ? 'yellow' : '#999';
        article.favoriteNum += article.favorited ? 1 : -1;
      }
      console.log(`${action} 操作后`, article);
      this.updateArticle(article);
    },
    async updateArticle(article) {
      try {
        console.log('发送给后端的数据:', article);
        const res = await updateArticle(article);
        console.log('更新成功', res.data);
      } catch (error) {
        console.error('更新失败', error);
      }
    },
  }
};
</script>

<style lang="scss">
.container {
  overflow: hidden;
}

.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}

.action-area {
  display: flex;
  align-items: center;
  cursor: pointer; /* 设置鼠标悬停时的样式 */
}

.action-button-text {
  margin-left: 5px;
}

button .uni-icons {
  margin-right: 5px;
}

/* 添加自定义滚动条样式 */
div[style*="overflow-y: auto;"]::-webkit-scrollbar {
  width: 8px;
}
div[style*="overflow-y: auto;"]::-webkit-scrollbar-track {
  background: #f1f1f1;
}
div[style*="overflow-y: auto;"]::-webkit-scrollbar-thumb {
  background: #888;
}
div[style*="overflow-y: auto;"]::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>